import { Resolver, Query, Args, ObjectType, Field } from '@nestjs/graphql';
import { useEntityManager } from '@sker/core';
import { FjFacilities, FjHotelEntity, FjHotelImage, FjPolicy, FjRoomImage, FjRoomType } from '@sker/entities';

@ObjectType()
export class HotelFactilityTypeItem {
    @Field()
    facilityName: string;
    @Field()
    facilityNameCn: string;
    @Field()
    facilityIsFree: string;
    @Field()
    facilityFeeDetail: string;
}
@ObjectType()
export class HotelFactilityType {
    @Field()
    facilityType: string;
    @Field(() => [HotelFactilityTypeItem])
    facilityItemList: HotelFactilityTypeItem[];
}

@ObjectType()
export class ImageItem {
    @Field()
    imageTag: string;
    @Field()
    url: string;
}
@ObjectType()
export class ImageList {
    @Field()
    imageType: string;
    @Field(() => [ImageItem])
    imageItemList: ImageItem[];
}
@ObjectType()
export class CheckinCheckoutTime {
    @Field({ nullable: true })
    checkinFrom: string;
    @Field({ nullable: true })
    checkinTo: string;
    @Field({ nullable: true })
    checkoutFrom: string;
    @Field({ nullable: true })
    checkoutTo: string;
}

@ObjectType()
export class PolicyList {
    @Field()
    policyType: string;
    @Field()
    policyDetail: string;
    @Field()
    policyDetailCn: string;
}

@ObjectType()
export class BroadNet {
    @Field()
    broadNetType: number;
    @Field()
    broadNetFee: string;
    @Field()
    broadNetFeeDesc: string;
}
@Resolver()
export class GraphqlProvider {

    /**
     * todo 酒店设施替换
     * @param hotel_id 
     * @returns 
     */
    @Query(() => [HotelFactilityType])
    async hotelFacilityItemList(
        @Args('hotel_id') hotel_id: string,
    ) {
        const list = await useEntityManager(async m => {
            const hotel = await m.findOne(FjHotelEntity, { where: { id: hotel_id }, select: { hotelid: true, from: true } })
            if (!hotel) return [];
            const list = await m.find(FjFacilities, { where: { sourceid: hotel.hotelid, from: hotel.from }, select: { name: true, name_cn: true } })
            const facilities: HotelFactilityType[] = [
                { // 餐饮服务
                    facilityType: '1',
                    facilityItemList: []
                },
                { // 厨房设施
                    facilityType: '2',
                    facilityItemList: []
                },
                { // 儿童设施/服务
                    facilityType: '3',
                    facilityItemList: []
                },
                { // 房间设施
                    facilityType: '4',
                    facilityItemList: []
                },
                { // 商务设施
                    facilityType: '5',
                    facilityItemList: []
                },
                { // 通用设施
                    facilityType: '6',
                    facilityItemList: []
                },
                { // 网络
                    facilityType: '7',
                    facilityItemList: []
                },
                { // 卫浴设施
                    facilityType: '8',
                    facilityItemList: []
                },
                { // 休闲娱乐
                    facilityType: '9',
                    facilityItemList: []
                },
                { // 其他设施
                    facilityType: '10',
                    facilityItemList: []
                },
                { // 互联网/媒体
                    facilityType: '11',
                    facilityItemList: []
                },
                { // 交通服务
                    facilityType: '12',
                    facilityItemList: []
                },
                { // 前台服务
                    facilityType: '13',
                    facilityItemList: []
                },
                {
                    facilityType: '100',
                    facilityItemList: []
                }
            ];
            list.map(it => {
                const facilityIsFree = it.name.includes('surcharge') ? 'F' : 'T';
                let facilityFeeDetail = ``
                const result = it.name.match(/surcharge\)\d+/)
                if (result && result.length === 2) {
                    const [all, money] = result;
                    facilityFeeDetail = money
                }
                let data: HotelFactilityTypeItem = {
                    facilityIsFree,
                    facilityFeeDetail,
                    facilityName: it.name,
                    facilityNameCn: it.name_cn
                }
                // 餐饮服务
                if (it.name.includes('Breakfast') || it.name.includes('Cookware')) {
                    const item = facilities.find(it => it.facilityType === '1')
                    item.facilityItemList.push(data)
                }
                // 厨房设施
                else if (it.name.includes('Barbecue')) {
                    const item = facilities.find(it => it.facilityType === '2')
                    item.facilityItemList.push(data)
                }
                // 儿童设施/服务
                else if (it.name.includes('child') || it.name.includes('Children')) {
                    const item = facilities.find(it => it.facilityType === '3')
                    item.facilityItemList.push(data)
                }
                // 房间设施
                else if (
                    it.name.startsWith('Air conditioning') ||
                    it.name.includes('curtain') ||
                    it.name.includes('Balcony') ||
                    it.name.includes('Bedding') ||
                    it.name.includes('Ceiling fan') ||
                    ['Air cleaner', 'Air detector', 'Alarm clock'].includes(it.name)
                ) {
                    const item = facilities.find(it => it.facilityType === '4')
                    item.facilityItemList.push(data)
                }
                // 商务设施
                else if (
                    it.name.includes('business center') ||
                    it.name.includes('Conference space size') ||
                    it.name.includes('Concierge')
                ) {
                    const item = facilities.find(it => it.facilityType === '5')
                    item.facilityItemList.push(data)
                }
                // 卫浴设施
                else if (
                    it.name.toLowerCase().includes('bathroom') ||
                    it.name.toLowerCase().includes('bathtub') ||
                    it.name.toLowerCase().includes('bidet')
                ) {
                    const item = facilities.find(it => it.facilityType === '8')
                    item.facilityItemList.push(data)
                }
                // 休闲娱乐
                else if (
                    ['Tours/ticket assistance'].includes(it.name) ||
                    it.name.includes('fitness') ||
                    it.name.includes(`game`) ||
                    it.name.includes(`Bar`) ||
                    it.name.includes(`lounge`) ||
                    it.name.includes('Billiards') ||
                    it.name.includes('Books') || it.name.includes('Coffee')
                ) {
                    const item = facilities.find(it => it.facilityType === '9')
                    item.facilityItemList.push(data)
                }
                // 其他设施
                else if (it.name.includes('socket')) {
                    const item = facilities.find(it => it.facilityType === '10')
                    item.facilityItemList.push(data)
                }
                // 多媒体
                else if (
                    ['Digital TV service', 'Cable channels', 'Cable TV service', 'CD player'].includes(it.name)
                    || it.name.includes('Computer')
                ) {
                    const item = facilities.find(it => it.facilityType === '11')
                    item.facilityItemList.push(data)
                }

                // 交通
                else if (it.name.includes('transportation') || it.name.includes('shuttle') || it.name.includes('parking')) {
                    const item = facilities.find(it => it.facilityType === '12')
                    item.facilityItemList.push(data)
                }
                // 前台服务
                else if (it.name.includes('front desk') || it.name.includes('ATM/banking')) {
                    const item = facilities.find(it => it.facilityType === '13')
                    item.facilityItemList.push(data)
                }

                else {
                    const item = facilities.find(it => it.facilityType === '100')
                    item.facilityItemList.push(data)
                }

            })
            return facilities;
        })
        return list;
    }

    @Query(() => [HotelFactilityType])
    async roomFacilityItemList(
        @Args('room_id') room_id: string,
    ) {
        /**
         * 1 浴室
            2 食品饮品
            3 便利设施
            4 互联网/媒体
            100 其他
         */
        const list = await useEntityManager(async m => {
            const hotel = await m.findOne(FjRoomType, { where: { id: room_id }, select: { room_type_id: true, from: true } })
            if (!hotel) return [];
            const list = await m.find(FjFacilities, { where: { type: 'RoomFacility', sourceid: hotel.room_type_id, from: hotel.from }, select: { name: true, name_cn: true } })
            const facilities: HotelFactilityType[] = [
                { // 浴室
                    facilityType: '1',
                    facilityItemList: []
                },
                { // 食品饮品
                    facilityType: '2',
                    facilityItemList: []
                },
                { // 便利设施
                    facilityType: '3',
                    facilityItemList: []
                },
                { // 互联网/媒体
                    facilityType: '4',
                    facilityItemList: []
                },
                {
                    facilityType: '100',
                    facilityItemList: []
                }
            ];
            list.map(it => {
                const facilityIsFree = it.name.includes('surcharge') ? 'F' : 'T';
                let facilityFeeDetail = ``
                const result = it.name.match(/surcharge\)\d+/)
                if (result && result.length === 2) {
                    const [all, money] = result;
                    facilityFeeDetail = money
                }
                let data: HotelFactilityTypeItem = {
                    facilityIsFree,
                    facilityFeeDetail,
                    facilityName: it.name || it.name_cn,
                    facilityNameCn: it.name_cn || it.name
                }
                // 便利设施
                if (
                    [
                        'Air conditioning', 'Desk', 'Linens provided', 'Curtain',
                        'Central air conditioning', 'Bedding: blankets or quilt',
                        'Refrigerator', 'Microwave', 'Heating', 'Iron/ironing board',
                        'Cookware, dishware, and utensils', 'Shower'
                    ].includes(it.name)
                ) {
                    const item = facilities.find(it => it.facilityType === '3')
                    item.facilityItemList.push(data)
                }
                // 浴室
                else if (
                    [
                        'Private bathroom', 'Towels provided', 'Free toiletries',
                        'Hair dryer', 'Shower only', 'Slippers', 'Separate shower room', 'Hairdryer'
                    ].includes(it.name)
                ) {
                    const item = facilities.find(it => it.facilityType === '1')
                    item.facilityItemList.push(data)
                }
                // 互联网/媒体
                else if (
                    [
                        'wi-fi',
                        'wifi'
                    ].includes(it.name.toLowerCase()) ||
                    ['Television', 'Free WiFi', 'In-room Wi-Fi', 'TV', 'Satellite TV service', 'Flat-panel TV', 'LCD TV', 'Cable TV service', 'Phone', 'Free in-room Wi-Fi'].includes(it.name)
                ) {
                    const item = facilities.find(it => it.facilityType === '4')
                    item.facilityItemList.push(data)
                }
                else if (
                    ['Electric kettle', 'Hot water (24 hours)', 'Coffee/tea maker', 'Free bottled water'].includes(it.name)
                ) {
                    const item = facilities.find(it => it.facilityType === '2')
                    item.facilityItemList.push(data)
                }
                else {
                    const item = facilities.find(it => it.facilityType === '100')
                    item.facilityItemList.push(data)
                }
            })
            return facilities.filter(it => it.facilityItemList.length > 0);
        })
        return list;
    }
    // 吸烟信息
    @Query(() => String)
    async roomSmoking(
        @Args('room_id') room_id: string,
    ) {
        return await useEntityManager(async m => {
            const hotel = await m.findOne(FjRoomType, { where: { id: room_id }, select: { room_type_id: true, from: true } })
            if (!hotel) return '3';
            const list = await m.find(FjFacilities, { where: { type: 'RoomFacility', sourceid: hotel.room_type_id, from: hotel.from }, select: { name: true, name_cn: true } })
            return this._roomSmoking(list)
        })
    }

    private _roomSmoking(list: FjFacilities[]) {
        const item = list.find(it => it.name === 'Non-Smoking')
        if (item) return '2' // 无
        const smoking = list.find(it => it.name === 'Smoking')
        if (smoking) return '1'
        return '3' // 未知
    }

    // 公共浴室
    private _roomSharedBathRoom(list: FjFacilities[]) {
        const item = list.find(it => it.name === 'Private bathroom' || it.name === 'Private bathroom (not in room)' || it.name === 'Private bathroomtrue' || it.name === 'Private bathroom0')
        if (item) return '2' // 否
        const share = list.find(it => it.name === 'Shared bathroom' || it.name === 'Shared bathroom with sink in room' || it.name === 'Shared bathroomtrue')
        if (share) return '1' // 是
        return '0' // 未知
    }

    private _roomBroadNet(list: FjFacilities[]): BroadNet[] {
        const broadNets: BroadNet[] = [];
        const item = list.find(it => [
            'wi-fi',
            'wifi'
        ].includes(it.name.toLowerCase()))
        if (!item) return broadNets;
        const facilityIsFree = item.name.includes('surcharge') ? 'F' : 'T';
        let facilityFeeDetail = ``
        const result = item.name.match(/surcharge\)\d+/)
        if (result && result.length === 2) {
            const [all, money] = result;
            facilityFeeDetail = money
        }
        if (item) {
            broadNets.push({
                broadNetType: 1,
                broadNetFee: "T",
                broadNetFeeDesc: ""
            })
        }
        const network = list.find(it => it.name.includes('Internet'))
        if (network) {
            broadNets.push({
                broadNetType: 2,
                broadNetFee: facilityIsFree,
                broadNetFeeDesc: facilityFeeDetail
            })
        }
        return broadNets;
    }

    // 公共浴室
    @Query(() => String)
    async roomSharedBathRoom(
        @Args('room_id') room_id: string,
    ) {
        return await useEntityManager(async m => {
            const hotel = await m.findOne(FjRoomType, { where: { id: room_id }, select: { room_type_id: true, from: true } })
            if (!hotel) return [];
            const list = await m.find(FjFacilities, { where: { type: 'RoomFacility', sourceid: hotel.room_type_id, from: hotel.from }, select: { name: true, name_cn: true } })
            return this._roomSharedBathRoom(list)
        })
    }

    /**
     * 网络信息集合
     */
    @Query(() => [BroadNet])
    async roomBroadNet(
        @Args('room_id') room_id: string,
    ): Promise<BroadNet[]> {
        return await useEntityManager(async m => {
            const hotel = await m.findOne(FjRoomType, { where: { id: room_id }, select: { room_type_id: true, from: true } })
            if (!hotel) return [];
            const list = await m.find(FjFacilities, { where: { type: 'RoomFacility', sourceid: hotel.room_type_id, from: hotel.from }, select: { name: true, name_cn: true } })
            return this._roomBroadNet(list)
        })
    }

    @Query(() => [ImageList])
    async roomImageList(
        @Args('room_id') room_id: string,
    ) {
        const list = await useEntityManager(async m => {
            const hotel = await m.findOne(FjRoomType, { where: { id: room_id }, select: { room_type_id: true, from: true } })
            if (!hotel) return [];
            const list = await m.find(FjRoomImage, { where: { roomid: hotel.room_type_id, from: hotel.from }, select: { image_url: true } })
            const imageList: ImageList[] = [
                {
                    imageType: '100',
                    imageItemList: list.map(it => {
                        return {
                            imageTag: ``,
                            url: it.image_url
                        } as ImageItem;
                    })
                }
            ];
            return imageList;
        })
        return list;
    }
    /**
     * 酒店的图片列表替换
     * @param hotel_id 
     * @returns 
     */
    @Query(() => [ImageList])
    async hotelImageList(
        @Args('hotel_id') hotel_id: string,
    ): Promise<ImageList[]> {
        const list = await useEntityManager(async m => {
            const hotel = await m.findOne(FjHotelEntity, { where: { id: hotel_id }, select: { hotelid: true, from: true } })
            if (!hotel) return [];
            const list = await m.find(FjHotelImage, { where: { hotelid: hotel.hotelid, from: hotel.from }, select: { caption: true, image_url: true } })
            const imageList: ImageList[] = [
                {
                    imageType: '100',
                    imageItemList: list.map(it => {
                        return {
                            imageTag: it.caption,
                            url: it.image_url
                        } as ImageItem;
                    })
                }
            ];
            return imageList;
        })
        return list;
    }
    /**
     * todo 酒店的入住离开时间限制
     * @param hotel_id 
     * @returns 
     */
    @Query(() => CheckinCheckoutTime, { nullable: true })
    async hotelCheckinCheckoutTime(
        @Args('hotel_id') hotel_id: string,
    ): Promise<any> {
        return {}
    }

    @Query(() => [PolicyList])
    async hotelPolicyList(
        @Args('hotel_id') hotel_id: string,
    ): Promise<PolicyList[]> {
        const list = await useEntityManager(async m => {
            const hotel = await m.findOne(FjHotelEntity, { where: { id: hotel_id }, select: { hotelid: true, from: true } })
            if (!hotel) return [];
            const list = await m.find(FjPolicy, { where: { sourceid: hotel.hotelid, from: hotel.from }, select: { content: true, content_cn: true, type: true } })
            return list.map(item => {
                const data = {
                    policyDetail: item.content,
                    policyDetailCn: item.content_cn
                } as PolicyList
                if (item.type === 'Pets') {
                    data.policyType = '2'
                }
                if (item.type === 'Other') {
                    data.policyType = '100'
                }
                if (item.type === 'Child') {
                    data.policyType = '1'
                }
                if (item.type === 'Meal') {
                    data.policyType = '3'
                }
                if (data.policyType) return data;
            }).filter(it => !!it)
        })
        return list;
    }

    @Query(() => [String])
    async acceptedCreditCardList(
        @Args('hotel_id') hotel_id: string,
    ) {
        const list = await useEntityManager(async m => {
            const hotel = await m.findOne(FjHotelEntity, { where: { id: hotel_id }, select: { hotelid: true, from: true } })
            if (!hotel) return [];
            const list = await m.find(FjPolicy, { where: { sourceid: hotel.hotelid, from: hotel.from, type: 'Payment' }, select: { content: true, content_cn: true, type: true } })
            return list.map(item => {
                switch (item.content) {
                    case 'Alipay':
                        return `AliPay`
                    case 'Wechatpay':
                        return `WeChat`
                    case 'Visa Card':
                    case 'VisaVisa':
                    case 'Visa':
                    case 'Visa0 percent':
                        return 'VISA'
                    case 'Maestro':
                    case 'MasterCard':
                    case 'MasterCard0 percent':
                    case 'MasterCardMasterCard':
                        return `MasterCard`
                    case 'Discover':
                    case 'Discover Card':
                    case 'DiscoverDiscover':
                        return `Discover`
                    case 'Diners Club':
                    case 'Diners ClubDiners Club':
                        return 'Diners Club'
                    case 'JCB':
                    case 'JCB Card':
                    case 'JCB International':
                    case 'Jin Sui':
                        return 'JCB'
                    case 'American Express':
                    case 'American Express0 percent':
                    case 'American Express Card':
                    case 'American Expresstrue':
                        return "AMEX"
                    default:
                        return undefined
                }
            }).filter(it => !!it)
        })
        return list;
    }
}